package com.czh.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czh.constants.SystemConstants;
import com.czh.domain.ResponseResult;
import com.czh.domain.entity.Record;
import com.czh.domain.entity.User;
import com.czh.domain.vo.RecordVo;
import com.czh.enums.AppHttpCodeEnum;
import com.czh.mapper.RecordMapper;
import com.czh.service.RecordService;
import com.czh.service.UserService;
import com.czh.utils.BeanCopyUtils;
import com.czh.utils.SecurityUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Record)表服务实现类
 *
 * @author czh
 * @since 2024-05-17 21:05:59
 */
@Log4j2
@Service("recordService")
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {
    @Resource
    private UserService userService;
    @Override
    public ResponseResult<List<RecordVo>> getRecordList() {
        //如果没有登录就显示Root头像
        LambdaQueryWrapper<Record> recordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Long userid;
        try {
            userid=SecurityUtils.getUserId();
        }catch (Exception e){
            log.error("当前没有用户token");
            userid= Long.valueOf(SystemConstants.ROOT);
        }
        String avatar = userService.getById(userid).getAvatar();
        recordLambdaQueryWrapper.eq(Record::getCreateBy,userid);
        recordLambdaQueryWrapper.orderByDesc(Record::getCreateTime);

        List<RecordVo> recordVos = BeanCopyUtils.copyBeanList(list(recordLambdaQueryWrapper), RecordVo.class).stream().map(recordVo ->
                recordVo.setAvatar(avatar)).collect(Collectors.toList());
        if (recordVos.size()==0){
            recordVos.add(new RecordVo(avatar,"当你登录时，这将是专属于你的记录,"));
        }
        return ResponseResult.okResult(recordVos);
    }

    @Override
    public ResponseResult<Object> addRecord(Map<String, String> recordMsg) {
        Record record = new Record();
        record.setContent(recordMsg.get("record"));
        save(record);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<Object> deleteRecord(Integer id) {
        removeById(id);
        return ResponseResult.okResult();
    }
}

